<template>
    <view>
        <!-- pages/pay/pay.wxml -->
        <view class="address">
            <button @tap="chooseAddress">选择地址</button>
            <view v-if="address" class="address-info">
                <text>收货人：{{ address.userName }}</text>
                <text>电话：{{ address.telNumber }}</text>
                <text>地址：{{ address.provinceName }} {{ address.cityName }} {{ address.countyName }} {{ address.detailInfo }}</text>
            </view>
        </view>
        <view>
            <view class="title">购物车</view>
            <block v-for="(item, index) in goodsList" :key="index">
                <view class="cart-item">
                    <view class="image-box">
                        <image class="goods-image" :src="item.goods_small_logo" mode="aspectFill"></image>
                    </view>
                    <view class="goods-info">
                        <text class="name">商品名称：{{ item.goods_name }}</text>
                        <view class="goods-info-bottom">
                            <text class="price">￥{{ item.goods_price }}</text>
                            <text class="count">X {{ item.goods_count }}</text>
                        </view>
                    </view>
                </view>
            </block>
        </view>
        <view class="bottom-box">
            <view class="bottom">
                <view class="total-price">
                    <text class="price-start">
                        合计：
                        <text class="price">￥{{ totalPrice }}</text>
                    </text>
                    <text class="tips">包含运费</text>
                </view>
                <view class="settlement">
                    <button @tap="toPay">支付({{ totalQuantity }})</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
// pages/pay/pay.js
import request from '../../request/index.js';
export default {
    data() {
        return {
            address: null,
            goodsList: [],
            totalPrice: 0,
            totalQuantity: 0
        };
    },
    onLoad: function (options) {
        if (options.goodsList && options.totalPrice) {
            let goodsList = JSON.parse(decodeURIComponent(options.goodsList));
            let totalPrice = parseFloat(options.totalPrice).toFixed(2);
            let totalQuantity = goodsList.reduce((acc, item) => acc + item.goods_count, 0);
            this.setData({
                goodsList: goodsList,
                totalPrice: totalPrice,
                totalQuantity: totalQuantity
            });
        }
        if (options.addressInfo) {
            this.setData({
                address: JSON.parse(decodeURIComponent(options.addressInfo))
            });
        }
    },
    methods: {
        chooseAddress: function () {
            let that = this;
            uni.chooseAddress({
                success(res) {
                    that.setData({
                        address: {
                            userName: res.userName,
                            telNumber: res.telNumber,
                            provinceName: res.provinceName,
                            cityName: res.cityName,
                            countyName: res.countyName,
                            detailInfo: res.detailInfo
                        }
                    });
                },
                fail(err) {
                    console.error('chooseAddress fail:', err);
                }
            });
        },

        toPay: function () {
            const token = uni.getStorageSync('token');
            console.log(token);
            if (token) {
                this.createOrder(token);
            } else {
                uni.navigateTo({
                    url: '/pages/auth/auth?from=pay'
                });
            }
        },

        createOrder: function () {
            const token = uni.getStorageSync('token');
            if (!token) {
                uni.navigateTo({
                    url: '/pages/auth/auth?frompay'
                });
                return;
            }
            if (!this.address) {
                uni.showToast({
                    title: '请选择收货地址',
                    icon: 'none'
                });
                return;
            }
            const orderData = {
                order_price: this.totalPrice,
                consignee_addr: `${this.address.provinceName}${this.address.cityName}${this.address.countyName}${this.address.detailInfo}`,
                goods: this.goodsList.map((item) => ({
                    goods_id: item.goods_id,
                    goods_number: item.goods_count,
                    goods_price: item.goods_price
                }))
            };
            console.log('OrderData:', orderData);
            uni.request({
                url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/create',
                method: 'POST',
                header: {
                    Authorization: token
                },
                data: orderData,
                success: (res) => {
                    console.log(res);
                    if (res.statusCode === 200 && res.data.meta.status === 200) {
                        const orderNumber = res.data.message.order_number;
                        uni.setStorageSync('orderNumber', orderNumber);
                        function formatDate(date) {
                            const year = date.getFullYear();
                            const month = (date.getMonth() + 1).toString().padStart(2, '0');
                            const day = date.getDate().toString().padStart(2, '0');
                            let hour = date.getHours();
                            const minute = date.getMinutes().toString().padStart(2, '0');
                            const second = date.getSeconds().toString().padStart(2, '0');
                            const period = hour < 12 ? '上午' : '下午';
                            hour = hour % 12;
                            hour = hour ? hour : 12;
                            return `${year}-${month}-${day},${period}${hour}:${minute}:${second}`;
                        }
                        const orderInfo = {
                            orderNumber: orderNumber,
                            orderPrice: this.totalPrice,
                            orderTime: formatDate(new Date())
                        };
                        let orders = uni.getStorageSync('orders') || [];
                        orders.push(orderInfo);
                        uni.setStorageSync('orders', orders);
                        console.log(orderNumber);
                        uni.request({
                            url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/req_unifiedorder',
                            method: 'POST',
                            header: {
                                Authorization: token
                            },
                            data: {
                                order_number: orderNumber
                            },
                            success(res) {
                                console.log(res);
                                if (res.statusCode === 200 && res.data.meta.status === 200) {
                                    //const payData = res.data.message;
                                    uni.requestPayment({
                                        timeStamp: String(Date.now()),
                                        nonceStr: 'nonceStr',
                                        package: 'prepay_id=wx12345678901234567890123456789012',
                                        signType: 'MD5',
                                        paySign: 'paySign',
                                        success(payRes) {
                                            console.log('支付成功', payRes);
                                        },
                                        fail(payErr) {
                                            console.error('支付失败', payErr);
                                            uni.showToast({
                                                title: '支付失败',
                                                icon: 'none'
                                            });
                                            return;
                                        }
                                    });
                                } else {
                                    console.error('获取支付参数失败', res.data);
                                }
                            },
                            fail(err) {
                                console.error('请求失败:', err);
                            }
                        });
                    }
                }
            });
        }
    }
};
</script>
<style>
/* pages/pay/pay.wxss */
.address {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 175rpx;
    border-bottom: 1rpx solid rgb(230, 227, 227);
}
.title {
    margin-left: 15rpx;
    font-size: xx-large;
    font-weight: 500;
}
.cart-item {
    width: 100%;
    height: 250rpx;
    display: flex;
    align-items: center;
}
.image-box {
    width: 250rpx;
    height: 190rpx;
    margin-right: 25rpx;
}
.goods-image {
    width: 250rpx;
    height: 190rpx;
}
.goods-info {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    height: 250rpx;
}
.goods-info-bottom {
    display: flex;
    justify-content: space-between;
}
.name {
    color: grey;
    font-size: medium;
}
.price {
    color: red;
    font-size: larger;
}
.count {
    margin-right: 15rpx;
    color: grey;
    font-size: medium;
}
.bottom-box {
    position: fixed;
    bottom: 0;
}
.bottom {
    display: flex;
    align-items: center;
}
.total-price {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 380rpx;
    margin-left: 135rpx;
}
.price-start {
    font-size: large;
}
.price {
    color: red;
}
.tips {
    color: black;
}
.settlement button {
    font-size: larger;
    background-color: red;
    color: white;
    width: 200rpx;
    margin-left: 15rpx;
}
</style>
